<?php
/**
* 极光推送模块 工具类
*
* 极光推送模块 工具类的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\Jpush;

use Illuminate\Support\Facades\Log;
use JPush\Client as JPushClient;
use JPush\Exception\APIConnectionException;
use JPush\Exception\APIRequestException;
use Illuminate\Support\Facades\DB;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\DataBase\SQL;

class JpushTool
{

    /**
     * 推送用户消息
     * @param $user_id 可传userid数组 array
     * @param $plat    平台
     * @param $message
     * @param array $extras
     * @param platform  平台
     * @param audience  设备
     * @param notification  内容
     * @return 正确返回true
     */
    public static function push($message,$plat=0,$user_id=0,$extras=null){
        $app_key=env('JPUSHAPPKEY_PHONE');
        $master_secret = env('JPUSHMASTERSECRET_PHONE');

        if($app_key=='JPUSHAPPKEY_PHONE'||$master_secret=='JPUSHMASTERSECRET_PHONE')
        {
            //发送失败
            return false;
        }

        $client = new JPushClient($app_key, $master_secret);
        try {
            $result = $client->push();
            $result->setNotificationAlert($message);
            //设置平台
            if($plat==0){
                //全平台
                $result->setPlatform('all');

                $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));

            }else{
                //个别平台
                if(count($plat)==1){
                    $result->setPlatform($plat);
                    if($plat[0]=='ios'){
                        $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                    }else if($plat[0]=='android'){
                        $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));
                    }else{
                        //return 1;
                        return false;
                    }
                }else if(count($plat)==2){
                    $result->setPlatform($plat);
                    $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                    $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));
                }else{
                    //return 2;
                    return false;
                }
            }

            if($user_id==0){
               $result ->addAllAudience();
            }else{
               $result ->addAlias($user_id);
            }

            $result->options(['apns_production' => false]);


            //插入push_message

            //dd($user_id);

            $push   = ['push_no'     => GeneralTool::only_no(),
                       'title'       => (empty($extras['title'])?'':$extras['title']),
                       'user_id'     => $user_id,
                       'class'       => (empty($extras['class'])?'system':$extras['class']),
                       'type'        => (empty($extras['type'])?0:$extras['type']),
                       'message'     => (isset($extras['message'])?$extras['message']:''),
                       'jump_value'  => (isset($extras['jump_value'])?$extras['jump_value']:''),
                       'template_no' => (isset($extras['template_no'])?$extras['template_no']:''),
                       'created_at'  => (empty($extras['time'])?time():$extras['time'])];
            $re = SQL::insert(['table' => 'push_messages',
                               'insert'=> $push]);

            if($re && is_array($extras['images'])){
                foreach($extras['images'] as $image){
                    // Log::info($image);
                    if(!isset($image['original_image']) || !isset($image['thumbnail'])) continue;
                    SQL::insert(['table'  => 'push_message_images',
                                 'insert' => ['push_no'        => $push['push_no'],
                                              'original_image' => $image['original_image'],
                                              'thumbnail'      => $image['thumbnail'],
                                              'state'          => 1,
                                              'created_at'     => time()]]);
                }
            }

            //$result->setOptions();
            $result = $result ->send();
            //dd($result);
//          Log::info('jpush:user_id'.$user_id.';sendno:'.$result->sendno.';msg_id:'.$result->msg_id.';extras:'.json_encode($extras));
            return true;
        } catch (\Exception $e) {
            try{
                Log::error('jpush:'.$e);
            }catch(\Exception $e){

            }
        }
        return true;
    }

    public static function push_ipad($message,$plat=0,$user_id=0,$extras=null){
        $app_key=env('JPUSHAPPKEY');
        $master_secret = env('JPUSHMASTERSECRET');
        //dd($app_key,$master_secret);
        if($app_key=='JPUSHAPPKEY'||$master_secret=='JPUSHMASTERSECRET')
        {
            //发送失败
            return false;
        }

        $client = new JPushClient($app_key, $master_secret);
        try {
            $result = $client->push();
            //设置平台
            if($plat==0){
                //全平台
                $result->setPlatform('all');
                $result->setNotificationAlert($message);
                $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));

            }else{
                //个别平台
                if(count($plat)==1){
                    $result->setPlatform($plat);
                    if($plat[0]=='ios'){
                        $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                    }else if($plat[0]=='android'){
                        $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));
                    }else{
                        //return 1;
                        return false;
                    }
                }else if(count($plat)==2){
                    $result->setPlatform($plat);
                    $result->iosNotification($message,
                                          array(
                                            'sound' => 'sound.caf',
                                        //  'badge' => '+1',
                                        //  'content-available' => true,
                                        //  'mutable-content' => true,
                                            'category' => 'jiguang',
                                            'extras' => $extras
                                        ));
                    $result->androidNotification($message,
                                           array(
                                        //  'build_id' => 2,
                                            'extras' => $extras
                                        ));
                }else{
                    //return 2;
                    return false;
                }
            }

            if($user_id==0){
               $result ->addAlias('all');
            }else{
               $result ->addAlias($user_id);
            }

            $result->options(['apns_production' => false]);
            //dd($result);
            $result = $result ->send();
            //插入push_message

            if(DB::table('push_messages')->where(array('title'=>(empty($extras['title'])?$extras['title']:''),
                                                       'user_id'=>$user_id,
                                                       'class'=>(empty($extras['class'])?'system':$extras['class']),
                                                       'type'=>(empty($extras['type'])?0:$extras['type']),
                                                       'message'=>(isset($extras['messages'])?$extras['messages']:''),
                                                       'jump_value'=>(isset($extras['jump_value'])?$extras['jump_value']:''),
                                                       'template_no'=>(isset($extras['template_no'])?$extras['template_no']:''),
                                                       'created_at'=>(empty($extras['time'])?time():$extras['time'])))
                                         ->count()==0){
                DB::table('push_messages')->insert(array('title'=>(empty($extras['title'])?$extras['title']:''),
                                                         'user_id'=>$user_id,
                                                         'class'=>(empty($extras['class'])?'system':$extras['class']),
                                                         'type'=>(empty($extras['type'])?0:$extras['type']),
                                                         'message'=>(isset($extras['messages'])?$extras['messages']:''),
                                                         'jump_value'=>(isset($extras['jump_value'])?$extras['jump_value']:''),
                                                         'template_no'=>(isset($extras['template_no'])?$extras['template_no']:''),
                                                         'created_at'=>(empty($extras['time'])?time():$extras['time'])));
            }

            Log::info('jpush:user_id'.$user_id.';sendno:'.$result->sendno.';msg_id:'.$result->msg_id.';extras:'.json_encode($extras));

            return true;
        } catch (\Exception $e) {
            try{
                Log::error('jpush:'.$e);
            }catch(\Exception $e){

            }
        }
        return true;
    }
}
